package com.shuangti.seatausermanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.shuangti.seatausermanagement.entity.User;
import com.shuangti.seatausermanagement.mapper.UserMapper;
import com.shuangti.seatausermanagement.service.UserManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


@Service
public class UserManagementServiceImpl implements UserManagementService {
    public static PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Autowired
    UserMapper userMapper;

    @Override
    public void addUser(User user) {
        user.setCreated_at(LocalDateTime.now());
        user.setPassword("{bcrypt}" + passwordEncoder().encode(user.getPassword()));
        userMapper.insert(user);
    }

    @Override
    public void deleteUser(Long user_id) {
        userMapper.deleteUserById(user_id);
    }

    @Override
    public boolean updateUserInfo(User user) {
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();

        updateWrapper.eq(User::getUser_id, user.getUser_id());


        updateWrapper.set(user.getUsername() != null, User::getUsername, user.getUsername())
                .set(user.getPassword() != null, User::getPassword, passwordEncoder().encode(user.getPassword()))
                .set(user.getEmail() != null, User::getEmail, user.getEmail())
                .set(user.getPhone() != null, User::getPhone, user.getPhone())
                .set(true,User::getUpdated_at,LocalDateTime.now());
        return userMapper.update(null, updateWrapper) > 0;
    }
}
